package com.haidong.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 本过滤器主要实现对网页资源调用前判断用户是否登录从而给出不同的回应
 */
@WebFilter("/*")
public class FilterDemo2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 由于servletRequest中没有获取session的方法,所以强转成HttpServlet
        HttpServletRequest req = (HttpServletRequest) servletRequest;

        // 最开始要验证用户是否是进行登录和注册操作,如果是这两种操作不必验证登录状态
        // 如果登录请求也被过滤并且再次跳转到登录页面,造成登录不了的死锁
        // 解决办法就是把登录和注册的相关资源优先通过
        String[] urls = {"/login.jsp","/imgs","/css","/loginServlet","/register.jsp","/registerServlet"};
        // 获取当前请求的访问路径是否包含登录注册内容
        String url = req.getRequestURL().toString();

        for (String u : urls) {
            if(url.contains(u)){
                filterChain.doFilter(servletRequest,servletResponse);
                // 如果这里使用break的话,后面还要判断是否登录
                // 在逻辑上是不通的,因为用户此时想要登录或者注册,不需要判断登录状态了
                return ;
            }
        }

        //在session中获取是否已经登录了
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");

        if(user==null){
            // 没登录就存储提示信息,跳转到登录界面
            req.setAttribute("login_msg","您尚未登录");
            req.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
        }else{
            // 登录成功了就放行资源
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
